package com.spring.api.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spera.genutil.TokenUtil;
import com.spring.api.web.service.UserApiService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.User;
import com.spring.security.web.service.UserService;
import com.spring.sperapc.web.model.Family;
import com.spring.sperapc.web.model.FamilyMember;
import com.spring.sperapc.web.service.FamilyMemberService;
import com.spring.sperapc.web.service.UserCommonService;
import com.spring.sperapc.web.service.UserDetailService;
import com.spring.sperapc.web.service.UserFamilyService;

/**
 * 
 * @author wojunyu
 * 
 */
@Controller
@RequestMapping(value = "/userApi")
public class UserApiController {
	static Logger logger = Logger.getLogger(UserApiController.class.getName());
	@Resource
	private UserService userService;
	@Resource
	private UserDetailService userDetailService;
	@Resource
	private JedisCache jedisCache;
	@Resource
	private UserFamilyService userFamilyService;
	@Resource
	private FamilyMemberService familyMemberService;
	
	@Resource
	private UserApiService userApiService;

	/**
	 * 查询家庭信息(包括了成员信息)v1.0
	 * 
	 * @param userDetail
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/queryFamily"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object queryFamily(String token, String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			Map<String, Object> k = TokenUtil.checkToken(token,jedisCache);
			if (ApplicationUtils.isNotNull(k)) {
				if (ApplicationUtils.isNotNull(callback))
					return new JSONPObject(callback, k);
				else
					return k;
			}

			String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
//			logger.info("queryFamily----->user_id:"+user_id);
			Map<String, String> s = new HashMap<String, String>();
			s.put("c_user_id", user_id);
			Family family = userFamilyService.selectByPrimaryKey(s);
			List<Family> dataSet = new ArrayList<Family>();
			dataSet.add(family);
			m.put(ApplicationUtils.DATASET, dataSet);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}

		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}

	/**
	 * 保存家庭信息（包括新增、修改）v1.1
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/saveUserFamily"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object saveUserFamily(Family family, String token, String callback,HttpServletRequest request){
		Map<String, Object> m = new HashMap<String, Object>();
		String ret = "";
		try {
			Map<String, Object> k = TokenUtil.checkToken(token,jedisCache);
			if (ApplicationUtils.isNotNull(k)) {
				if (ApplicationUtils.isNotNull(callback))
					return new JSONPObject(callback, k);
				else
					return k;
			}

			String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
//			logger.info("saveUserFamily----->user_id:"+user_id);
			User u = new User();
			u.setId(user_id);
			// Map<String, Object> retD = new HashMap<String, Object>();
			//家庭信息更新
//			if (ApplicationUtils.isNotNull(family.getId())) {
				userFamilyService.updateByPrimaryKeySelective(family);
				m.put(ApplicationUtils.STATUS, "1");
				ret = "操作成功";
//			} else {//家庭信息新增
//				//判断家庭是否已存在
//				Map<String, String> s = new HashMap<String, String>();
//				s.put("c_user_id", user_id);
//				Family isIn = userFamilyService.selectByPrimaryKey(s);
//				if(!ApplicationUtils.isNotNull(isIn)){
//					family.setId(ApplicationUtils.randomUUID());
//					userFamilyService.insertSelective(family, u);
//					m.put(ApplicationUtils.STATUS, "1");
//					ret = "操作成功";
//				}else{
//					m.put(ApplicationUtils.STATUS, "0");
//					ret = "家庭已存在,请刷新后重试";
//				}
//			}
			m.put(ApplicationUtils.MSG, ret);
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}

	/**
	 * 查询家庭成员v1.0
	 * 
	 * @param family
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/queryFamilyMember"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object queryFamilyMember(
			String c_family_id, String token,String c_user_id, String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			Map<String, Object> k = TokenUtil.checkToken(token,jedisCache);
			if (ApplicationUtils.isNotNull(k)) {
				if (ApplicationUtils.isNotNull(callback))
					return new JSONPObject(callback, k);
				else
					return k;
			}

			String user_id = jedisCache.hget(token,TokenUtil.USER_ID);
//			logger.info("queryFamilyMember----->user_id:"+user_id);
			Map<String, String> s = new HashMap<String, String>();
			if(ApplicationUtils.isNotNull(c_user_id)){
				s.put("c_user_id", c_user_id);
			}else if(ApplicationUtils.isNotNull(c_family_id)){
				s.put("c_family_id", c_family_id);
			}else{
				s.put("c_user_id", user_id);
			}

			List<FamilyMember> familyMemList = familyMemberService
					.selectByFamilyId(s);

			m.put(ApplicationUtils.DATASET, familyMemList);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}

	/**
	 * 新增家庭成员v1.0
	 * 
	 * @param family
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/saveMember"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object saveMember(FamilyMember familyMember, String token,
			String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
//		String ret = "";
		try {
			Map<String, Object> k = TokenUtil.checkToken(token,jedisCache);
			if (ApplicationUtils.isNotNull(k)) {
				if (ApplicationUtils.isNotNull(callback))
					return new JSONPObject(callback, k);
				else
					return k;
			}
			String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
//			logger.info("saveMember----->user_id:"+user_id);
			
//			if(!ApplicationUtils.isNotNull(familyMember.getUsername())){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "用户名不可为空");
//				return m;
			//通过添加家庭成员方式添加的账号用户名未uuid
				familyMember.setUsername(ApplicationUtils.randomUUID());
//			}
			if(!ApplicationUtils.isNotNull(familyMember.getPassword())){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "密码不可为空");
//				return m;
				familyMember.setPassword("123456");
			}
			if(!ApplicationUtils.isNotNull(familyMember.getSex())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "性别不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getBirthday())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "生日不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getMemberName())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "称谓不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getcRoleId())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "角色不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getReal_name())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "姓名不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getcFamilyId())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "家庭不可为空");
				return m;
			}
//			else if(!ApplicationUtils.isNotNull(familyMember.getPhone())){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "手机号不可为空");
//			//	return m;
//			}
			
//			if(!ApplicationUtils.isNotNull(familyMember.getReal_name())){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "真实名字不可为空");
//				return m;
//			}
			
//			else {
				String c_user_id=ApplicationUtils.randomUUID();
				
				familyMember.setC_user_id(c_user_id);
				String insert_ret = familyMemberService.insertSelective(familyMember);
				
				if("-1".equals(insert_ret)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该用户名已经被使用");
				}else if("0".equals(insert_ret)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "保存失败");
				}else if(insert_ret.equals("2")){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "不能多次插入父母角色");
				}
				
				else{
					
					List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
					
					Map<String, Object> hmr=new HashMap<String, Object>();
					hmr.put("c_user_id", c_user_id);
					list.add(hmr);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "保存成功");
				}
//			}
			
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}
	
	
	
	
	@RequestMapping(value = "/saveMembeBackground"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object saveMemberBackground(FamilyMember familyMember, String token,
			String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
		System.out.println("saveMembeBackground");
//		String ret = "";
		try {
			if(!ApplicationUtils.isNotNull(familyMember.getUsername())){
				familyMember.setUsername(ApplicationUtils.randomUUID());
			}
			if(!ApplicationUtils.isNotNull(familyMember.getPassword())){
				familyMember.setPassword("123456");
			}
			if(!ApplicationUtils.isNotNull(familyMember.getSex())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "性别不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getBirthday())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "生日不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getMemberName())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "称谓不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getcRoleId())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "角色不可为空");
				return m;
			}
			if(!ApplicationUtils.isNotNull(familyMember.getcFamilyId())){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "家庭不可为空");
				return m;
			}
				String c_user_id=ApplicationUtils.randomUUID();
				
				familyMember.setC_user_id(c_user_id);
				String insert_ret = familyMemberService.insertSelective(familyMember);
				
				if("-1".equals(insert_ret)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该用户名已经被使用");
				}else if("0".equals(insert_ret)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "保存失败");
				}else if(insert_ret.equals("2")){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "不能多次插入父母角色");
				}
				
				else{
					
					List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
					
					Map<String, Object> hmr=new HashMap<String, Object>();
					hmr.put("c_user_id", c_user_id);
					list.add(hmr);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "保存成功");
				}
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}
	
	
	
	
	
	/**
	 * 更新家庭成员信息v1.0
	 * @param familyMember
	 * @param token
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/updateMember"/*,method=RequestMethod.POST*/)
	@ResponseBody
	public Object updateMember(FamilyMember familyMember, String token,
			String callback,HttpServletRequest request) {
		Map<String, Object> m = new HashMap<String, Object>();
		String ret = "";
		try {
			Map<String, Object> k = TokenUtil.checkToken(token,jedisCache);
			if (ApplicationUtils.isNotNull(k)) {
				if (ApplicationUtils.isNotNull(callback))
					return new JSONPObject(callback, k);
				else
					return k;
			}
			String cFamilyId = jedisCache.hget(token, TokenUtil.FAMILY_ID);
			familyMember.setcFamilyId(cFamilyId);
			int iss = 0;
				iss = familyMemberService
						.updateByPrimaryKeySelective(familyMember,token,request);
			if (iss == 0) {
				ret = "操作失败";
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, ret);
			} else if(iss == 2){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "不能重复插入父母角色");				
			}	
			else {
				ret = "操作成功";
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, ret);
			}
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback))
			return new JSONPObject(callback, m);
		else
			return m;
	}

	 @RequestMapping(value = "/checkLogin")
	 @ResponseBody
	 public Object checkLogin(String token,String callback) {
		 Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);
		 if (!ApplicationUtils.isNotNull(s)) {
			 s = new HashMap<String, Object>();
			 s.put(ApplicationUtils.STATUS, "1");
			 s.put(ApplicationUtils.MSG, "有效用户");
		 }
		 if (ApplicationUtils.isNotNull(callback))
				return new JSONPObject(callback, s);
			else
				return s;
	 }
	 
	 /**
	  * 登出
	  * @param token
	  * @param callback
	  * @return
	  */
	 @RequestMapping(value = "/logOut")
	 @ResponseBody
	 public Object logOut(String token,String callback) {
		 Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);
		 if (!ApplicationUtils.isNotNull(s)) {
			 s = new HashMap<String, Object>();
			 jedisCache.del(token);
			 s.put(ApplicationUtils.STATUS, "1");
			 s.put(ApplicationUtils.MSG, "欢迎下次光临");
		 }
		 if (ApplicationUtils.isNotNull(callback))
				return new JSONPObject(callback, s);
			else
				return s;
	 }
	 
	 @RequestMapping(value = "/queryUsers")
	 @ResponseBody
	 public Object queryUsers(@RequestParam(required=true,value="c_user_ids[]") String[] c_user_ids,
			 String callback) {
		 Map<String, Object> m = new HashMap<String, Object>();
			try {
				if(c_user_ids==null){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "用户编号不可为空");
				}else{
					List<String> userlist = new ArrayList<String>();
					for(Object uid:c_user_ids){
						userlist.add(String.valueOf(uid));
					}
					List<Map<String,Object>> imagelist = userApiService.queryUserImage(userlist);
					m.put(ApplicationUtils.DATASET, imagelist);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");
				}
			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			if (ApplicationUtils.isNotNull(callback))
				return new JSONPObject(callback, m);
			else
				return m;
	 }
	 
	 
	 @RequestMapping(value = "/queryUsers2")
	 @ResponseBody
	 public Object queryUsers(String c_user_ids,
			 String callback) {
		 String[] userList=c_user_ids.split(",");
		 
		 Map<String, Object> m = new HashMap<String, Object>();
			try {
				if(c_user_ids==null){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "用户编号不可为空");
				}else{
					List<String> userlist = new ArrayList<String>();
					for(Object uid:userList){
						userlist.add(String.valueOf(uid));
					}
					List<Map<String,Object>> imagelist = userApiService.queryUserImage(userlist);
					m.put(ApplicationUtils.DATASET, imagelist);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");
				}
			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			if (ApplicationUtils.isNotNull(callback))
				return new JSONPObject(callback, m);
			else
				return m;
	 }
	 
	 
	 /**
	  * 登录用户根据token获取孩子信息
	  * @param token
	  * @param callback
	  * @return
	  */
	 @RequestMapping(value = "/getBabyByParent")
	 @ResponseBody
	 public Object getBabyByParent(String token,String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			m = userFamilyService.getBabyByParent(token);
			
		} catch (Exception e) {
			e.printStackTrace();
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	 }
		
	 /**
	  * 根据用户id获取孩子信息
	  * @param c_user_id
	  * @param callback
	  * @return
	  */
	 @RequestMapping(value = "/getBabyByParentId")
	 @ResponseBody
	 public Object getBabyByParentId(String c_user_id,String callback) {
		 Map<String, Object> m = new HashMap<String, Object>();
		 try {
			 m = userFamilyService.getBabyByParent(c_user_id);
			
		 } catch (Exception e) {
			 e.printStackTrace();
			 m.put(ApplicationUtils.STATUS, "0");
			 m.put(ApplicationUtils.MSG, "系统异常");
		 }

		 if (ApplicationUtils.isNotNull(callback)) {
			 return new JSONPObject(callback, m);
		 } else {
			 return m;
		 }
	 }
		
		
		
	 @RequestMapping(value = "/getRoleList")
	 @ResponseBody
	 public Object getRoleList(String callback) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			m = userFamilyService.getRoleList();
			
		} catch (Exception e) {
			e.printStackTrace();
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	 }
		
	 @Resource
	 private UserCommonService userCommonService;
		
		
	/**
     * 激活账号
     */
	@RequestMapping(value = "/enableUser")
	@ResponseBody
	public Object enableUser(String token, String c_user_id, String phone,
			String password,String valnum,String needValNum,String callback,HttpServletRequest request) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			m = userCommonService.enableUser(token,c_user_id,phone,password,valnum,needValNum,request);
			
		} catch (Exception e) {
			e.printStackTrace();
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

}
